<template>
  <div class="test-container">
    <el-form :inline="inline" :model="envInfo" size="mini">
      <el-form-item label="登录名">
        <el-input v-model="envInfo.user" placeholder="vone用户"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="envInfo.password" placeholder="vone密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="环境">
        <el-input v-model="envInfo.env" placeholder="环境，多个环境用‘，’分隔"></el-input>
      </el-form-item>
      <el-form-item label="分支">
        <el-input v-model="envInfo.tag" placeholder="分支"></el-input>
      </el-form-item>
      <el-button @click="query">查询</el-button>
      <el-button v-if="tabelInfo.serviceList.length" @click="intervalFlush">刷新服务</el-button>
      <el-button v-if="tabelInfo.serviceList.length" :disabled="tabelInfo.selections.length == 0" @click="buildAll">
        批量构建
      </el-button>
      <el-button v-if="tabelInfo.serviceList.length" :disabled="tabelInfo.selections.length == 0" @click="buildLast">
        重新构建
      </el-button>
      <el-button v-if="tabelInfo.serviceList.length" @click="showDialog">
        Excel导入构建
      </el-button>
    </el-form>
    <el-table
      :data="
        tabelInfo.serviceList.filter(
          data => !tabelInfo.search || data.serviceCode.toLowerCase().includes(tabelInfo.search.toLowerCase())
        )
      "
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="serviceId" label="id"></el-table-column>
      <el-table-column prop="serviceName" label="服务名"></el-table-column>
      <el-table-column prop="serviceCode" label="服务code"></el-table-column>
      <el-table-column prop="env" label="环境"></el-table-column>
      <el-table-column prop="runUser" label="最后运行人"></el-table-column>
      <el-table-column prop="lastTag" label="最后运行分支"></el-table-column>
      <el-table-column prop="lastTime" label="最后运行时间"></el-table-column>
      <el-table-column label="最后运行状态">
        <template #default="scope">
          <el-tag v-if="scope.row.status == 1" color="green" effect="dark">成功</el-tag>
          <el-tag v-else-if="scope.row.status == 2" color="red" effect="dark">失败</el-tag>
          <el-tag v-else-if="scope.row.status == 0" color="blue" effect="dark">运行中</el-tag>
          <el-tag v-else color="gray" effect="dark">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="right">
        <template #header>
          <el-input v-model="tabelInfo.search" size="mini" placeholder="输入关键字搜索" />
        </template>
        <template #default="scope">
          <!-- <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Edit</el-button> -->
          <el-button size="mini" v-if="scope.row.status != 0" type="danger" @click="buildOne(scope.row)"
            >构建</el-button
          >
          <el-button size="mini" v-if="scope.row.status != 0" type="danger" @click="rebuildOne(scope.row)"
            >重新构建</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="Excel导入构建" v-model="dialogVisible" width="80%" @close="closeDialog">
      <el-upload
        v-if="dialogInfo.file == null"
        action="/"
        drag
        :show-file-list="false"
        :on-change="importExcel"
        :auto-upload="false"
        :file-list="dialogInfo.fileList"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <el-form v-if="dialogInfo.file != null" :inline="inline" :model="dialogInfo.formInfo" size="mini">
        <el-form-item label="Sheet">
          <el-select v-model="dialogInfo.formInfo.sheet" placeholder="请选择">
            <el-option v-for="item in dialogOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务列">
          <el-select v-model="dialogInfo.formInfo.service" placeholder="请选择">
            <el-option v-for="item in dialogTables" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本列">
          <el-select v-model="dialogInfo.formInfo.version" placeholder="请选择">
            <el-option v-for="item in dialogTables" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-table
        v-if="dialogInfo.file != null"
        :data="dialogData"
        border
        @selection-change="handleDialogSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          v-for="(item, index) in dialogTables"
          :key="index"
          :prop="item"
          :label="item"
        ></el-table-column>
        <el-table-column align="right">
          <template #header>
            <el-input v-model="dialogInfo.search" size="mini" placeholder="输入关键字搜索" />
          </template>
          <template #default="scope">
            <el-select v-model="scope.row.serviceId" placeholder="请选择">
              <el-option
                v-for="item in matchStatus(scope.row)"
                :key="item.id"
                :label="item.serviceName"
                :value="item.serviceId"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="quitDialog()">取 消</el-button>
          <el-button @click="closeDialog()">重 置</el-button>
          <el-button type="primary" @click="buildExcel()">构 建</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, computed, onMounted } from 'vue'
// import { useStore } from "vuex";
import { queryService, buildService } from '@/api/vone'
import { ElMessage, ElLoading } from 'element-plus'
import XLSX from 'xlsx'

export default defineComponent({
  name: 'ServicesInfo',
  components: {},
  setup() {
    // const store = useStore();
    const envInfo = reactive({
      user: 'chenjunchuan@vv.cn',
      password: 'Cjmonky12037',
      env: 'worktest3',
      tag: 'prod'
    })
    const inline = ref(true)
    let flush = ref(false)
    let dialogVisible = ref(false)
    // let serviceList: any[] = reactive([])
    const tabelInfo = reactive({
      serviceList: [],
      search: '',
      selections: []
    })
    const dialogInfo = reactive({
      file: null,
      formInfo: {
        sheet: '',
        service: '',
        version: ''
      },
      excelList: [],
      search: '',
      selections: []
    })

    onMounted(() => {
      const localenv = localStorage.getItem('services')
      if (localenv) {
        const localobj = JSON.parse(localenv)
        envInfo.user = localobj.user || envInfo.user
        envInfo.password = localobj.password || envInfo.password
        envInfo.env = localobj.env || envInfo.env
        envInfo.tag = localobj.tag || envInfo.tag
      }
    })
    const query = function() {
      if (
        envInfo.user === null ||
        envInfo.user === undefined ||
        envInfo.user === '' ||
        envInfo.password === null ||
        envInfo.password === undefined ||
        envInfo.password === '' ||
        envInfo.env === null ||
        envInfo.env === undefined ||
        envInfo.env === ''
      ) {
        console.log('please input user & password')
        ElMessage.error('please input user & password')
        return
      }
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      flushService(true, loading)
      localStorage.setItem('services', JSON.stringify(envInfo))
    }

    const flushService = function(reflush: boolean, loading: any | undefined) {
      queryService({
        userName: envInfo.user,
        password: envInfo.password,
        env: envInfo.env,
        reFlush: reflush
      })
        .then(res => {
          console.log(res)
          if (res) {
            tabelInfo.serviceList = []
            res.data.forEach((r: any) => {
              ;(tabelInfo.serviceList as Array<any>).push(r)
            })
          }
          if (loading) {
            loading.close()
          }
        })
        .catch(() => {
          if (loading) {
            loading.close()
          }
        })
    }
    let interval: any = null
    const intervalFlush = function() {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      flushService(false, loading)
    }
    const startFlush = function() {
      interval = setInterval(intervalFlush, 30000)
      flush.value = true
    }
    const stopFlush = function() {
      if (interval.length > 0) {
        clearInterval(interval)
      }
      flush.value = false
    }
    const buildAll = function() {
      if (tabelInfo.selections.length === 0) {
        ElMessage.warning('请先选择服务')
        return
      }
      const buildInfo: any[] = []
      tabelInfo.selections.forEach((item: any) => {
        buildInfo.push({
          serviceCode: item.serviceCode,
          serviceId: item.serviceId,
          itemId: item.itemId,
          run: item.run,
          lastTag: envInfo.tag
        })
      })
      buildService({ userName: envInfo.user, serviceList: buildInfo }).then(() => {
        ElMessage.success('success')
      })
    }

    const buildLast = function() {
      if (tabelInfo.selections.length === 0) {
        ElMessage.warning('请先选择服务')
        return
      }
      const buildInfo: any[] = []
      tabelInfo.selections.forEach((item: any) => {
        buildInfo.push({
          serviceCode: item.serviceCode,
          serviceId: item.serviceId,
          itemId: item.itemId,
          run: item.run,
          lastTag: item.lastTag
        })
      })
      buildService({ userName: envInfo.user, serviceList: buildInfo }).then(() => {
        ElMessage.success('success')
      })
    }
    const buildOne = function(row: any) {
      buildService({
        userName: envInfo.user,
        serviceList: [
          {
            serviceCode: row.serviceCode,
            serviceId: row.serviceId,
            itemId: row.itemId,
            run: row.run,
            lastTag: envInfo.tag
          }
        ]
      }).then(() => {
        ElMessage.success('success')
      })
    }

    const rebuildOne = function(row: any) {
      buildService({
        userName: envInfo.user,
        serviceList: [
          {
            serviceCode: row.serviceCode,
            serviceId: row.serviceId,
            itemId: row.itemId,
            run: row.run,
            lastTag: row.lastTag
          }
        ]
      }).then(() => {
        ElMessage.success('success')
      })
    }
    const buildExcel = function() {
      if (dialogInfo.selections.length === 0) {
        ElMessage.warning('请先选择服务')
        return
      }
      if (dialogInfo.formInfo.version === '') {
        ElMessage.warning('请先选择分支列')
        return
      }
      const buildInfo: any[] = []
      dialogInfo.selections.forEach((item: any) => {
        if (item.serviceId !== '') {
          const service = tabelInfo.serviceList.filter((row: any) => {
            return row.serviceId === item.serviceId
          })
          buildInfo.push({
            serviceCode: (service[0] as any).serviceCode,
            serviceId: (service[0] as any).serviceId,
            itemId: (service[0] as any).itemId,
            run: (service[0] as any).run,
            lastTag: item[dialogInfo.formInfo.version]
          })
        }
      })
      buildService({ userName: envInfo.user, serviceList: buildInfo }).then(() => {
        ElMessage.success('success')
      })
      quitDialog()
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      flushService(false, loading)
    }
    const handleSelectionChange = function(val: any[]) {
      ;(tabelInfo.selections as Array<any>) = val
    }
    const showDialog = function() {
      dialogVisible.value = true
    }
    const handleDialogSelectionChange = function(val: any[]) {
      ;(dialogInfo.selections as Array<any>) = val
    }

    const importExcel = function(file: any) {
      ;(dialogInfo.file as any) = file
      const types = file.name.split('.')[1]
      const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(item => item === types)
      if (!fileType) {
        ElMessage.error('格式错误！请重新选择')
        return
      }
      file2Xce(file).then(tabJson => {
        if (tabJson) {
          ;(dialogInfo.excelList as Array<any>) = tabJson! as Array<any>
          if (dialogInfo.excelList.length > 0) {
            dialogInfo.formInfo.sheet = (dialogInfo.excelList[0] as any).sheetName
          }
        }
      })
    }
    const file2Xce = function(file: any) {
      return new Promise(resolve => {
        const reader = new FileReader()
        reader.onload = function(e) {
          const data = e.target!.result
          const wb = XLSX.read(data, {
            type: 'binary'
          })
          const result: any[] = []
          wb.SheetNames.forEach(sheetName => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(wb.Sheets[sheetName])
            })
          })
          resolve(result)
        }
        reader.readAsBinaryString(file.raw)
      })
    }

    const closeDialog = function() {
      dialogInfo.formInfo = {
        sheet: '',
        service: '',
        version: ''
      }
      dialogInfo.file = null
      dialogInfo.excelList = []
      dialogInfo.search = ''
      dialogInfo.selections = []
    }

    const quitDialog = function() {
      dialogVisible.value = false
      closeDialog()
    }

    const matchStatus = function(row: any) {
      const col = dialogInfo.formInfo.service
        ? dialogInfo.formInfo.service
        : dialogTables.value.length
        ? dialogTables.value[0]
        : ''
      const match = tabelInfo.serviceList.filter((item: any) => {
        return row[col].toLowerCase() === item.serviceCode.trim().toLowerCase()
      })
      return match
    }

    const dialogOptions = computed(() => {
      return dialogInfo.excelList.map((item: any) => {
        return item.sheetName
      })
    })
    const dialogData = computed(() => {
      const sheetData = dialogInfo.excelList.filter((data: any) => {
        return data.sheetName === dialogInfo.formInfo.sheet
      })
      if (sheetData.length == 0) {
        return []
      }
      const col = dialogInfo.formInfo.service
        ? dialogInfo.formInfo.service
        : dialogTables.value.length
        ? dialogTables.value[0]
        : ''
      const dialogD = (sheetData[0] as any).sheet.filter((data: any) => {
        return (
          !dialogInfo.search ||
          !dialogTables.value.length ||
          (typeof data[col] === 'string'
            ? data[col].toLowerCase().includes(dialogInfo.search.toLowerCase())
            : data[col]
                .toString()
                .toLowerCase()
                .includes(dialogInfo.search.toLowerCase()))
        )
      })
      dialogD.forEach((row: any) => {
        const service = matchStatus(row)
        row.serviceId = service.length ? (service[0]! as any).serviceId : ''
      })
      return dialogD
    })
    const dialogTables = computed(() => {
      const sheetData = dialogInfo.excelList.filter((data: any) => {
        return data.sheetName === dialogInfo.formInfo.sheet
      })
      const headers: any[] = []
      if (sheetData.length > 0 && (sheetData[0] as any).sheet.length > 0) {
        ;(sheetData[0] as any).sheet.forEach((s: any) => {
          Object.keys(s).forEach(key => {
            if (headers.indexOf(key) == -1 && key !== 'serviceId') {
              headers.push(key)
            }
          })
        })
      }
      return headers
    })

    return {
      envInfo,
      query,
      inline,
      tabelInfo,
      flushService,
      buildAll,
      buildOne,
      buildExcel,
      handleSelectionChange,
      dialogVisible,
      dialogInfo,
      importExcel,
      showDialog,
      handleDialogSelectionChange,
      dialogOptions,
      dialogData,
      dialogTables,
      closeDialog,
      matchStatus,
      quitDialog,
      flush,
      stopFlush,
      startFlush,
      buildLast,
      rebuildOne,
      intervalFlush
    }
  }
})
</script>
<style scoped>
.test-container {
  height: 100%;
}
</style>
